import React, {Component} from 'react';
import { withRouter } from "react-router-dom";
import NavBarMy from "../navbar/NavBarMy";
import { SearchBar } from "antd-mobile";
import {searchGoods} from '../../api/api';
import './Search.scss';
import style from './Search.module.scss'

class Search extends Component {
    state={
        goodsList:[]
    }
    Flag=null;
    clear=()=>{
        clearTimeout(this.Flag);
        this.Flag=null;
    }
    debounce=(fn,wait)=>{
        if(this.Flag){
            this.clear();
        }
        this.Flag=setTimeout(()=> {
            fn();
            this.clear();
        },wait)
    }
    throttle=(fn,wait)=>{
        if(!this.Flag){
            this.Flag=setTimeout(()=>{
                fn();
                this.clear();
            },wait)
        }
    }
    handleChange=(value)=>{
        this.throttle(async ()=>{
            let res=await searchGoods({query:value});
            this.setState({
                goodsList: res.message || [],
            });
        },500)
    }
    handleClick=(id)=>{
        this.props.history.push("goodDetail/" + id);
    }
    render() {
        return (
            <div>
                <NavBarMy title='搜索中心' left={true}></NavBarMy>
                <SearchBar
                    placeholder='搜索'
                    cancelText='搜索'
                    onChange={this.handleChange}
                ></SearchBar>
                <div className={style.searchBox}>
                    <div>{
                        this.state.goodsList.map((v)=>{
                            return (<div
                                className={style.searchItem}
                                key={v.goods_id}
                                onClick={()=>{this.handleClick(v.goods_id)}}
                            >
                                {v.goods_name}
                            </div>)
                        })
                    }</div>
                </div>
            </div>
        );
    }
}

export default withRouter(Search);
